<template>
  <div class="home-task">
    <!-- header -->
    <van-nav-bar
      title="任务"
      left-text="一键关闭"
      right-text="一键启动"
      class="home-task__nav"
      ref="header"
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />
    <!-- empty -->
    <van-empty v-if="iconItems.length === 0">
      <template #description>
        <span>暂无平台，请前往添加</span>
      </template>
    </van-empty>

    <!-- main -->
    <better-scroll class="home-task__wrapper" :data="iconItems">
      <van-grid :column-num="4" class="home-task__grid">
        <van-grid-item
          v-for="(item, index) in iconItems"
          :key="index"
          @click="onOpenPlatform(item, index)"
        >
          <span
            class="home-task__grid-type"
            :class="item.opened === '待启动' ? 'default' : item.opened === '已启动' ? 'active' : 'over'"
          >{{ item.opened }}</span>
          <van-image :src="item.icon" />
          <span>{{ item.label }}</span>
        </van-grid-item>
      </van-grid>
    </better-scroll>

    <!-- 一键启动 -->
    <van-overlay :show="isPercentage" @click="isPercentage = false" get-container="body">
      <div>总共{{ result.length }}个，正在启动第{{ percentage }}个，请耐心等待...</div>
    </van-overlay>

    <!-- 右侧弹窗 一键启动 -->
    <van-popup
      v-model="show"
      position="right"
      :style="{ width: '80%', height: '100%' }"
      ref="wrapper"
    >
      <div class="popup-modal">
        <van-nav-bar
          title="选择启动的平台"
          :right-text="toggleAll ? '反选' : '全选'"
          @click-right="onToggleAll"
        />
        <van-checkbox-group v-model="result" ref="checkboxGroup">
          <van-cell-group>
            <van-cell
              v-for="(item, index) in iconItems"
              clickable
              :key="index"
              :title="item.label"
              @click="onToggle(index)"
            >
              <template #right-icon>
                <van-checkbox :name="item" shape="square" checked-color="#e4393c" ref="checkboxes" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
        <van-cell-group class="popup-modal__btn">
          <van-button type="default" @click="show = !show">取消</van-button>
          <van-button type="danger" @click="onSure">确定</van-button>
        </van-cell-group>
      </div>
    </van-popup>

    <!-- 启动 -->
    <van-popup
      v-model="isShow"
      position="right"
      :style="{ width: '100%', height: '100%' }"
      ref="wrapper"
    >
      <div class="popup-open">
        <van-nav-bar :title="item.label" left-text="返回" left-arrow is-link @click-left="onBack">
          <template #right>
            <van-icon name="delete" size="16" @click="onDelete" />
            <van-icon name="plus" size="16" @click="onAdd" />
          </template>
        </van-nav-bar>
        <div class="popup-open__form">
          <!-- 响订单 -->
          <jingle-cat
            v-show="item.index === 0"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 丑小鸭 -->
          <duck
            v-show="item.index === 1"
            :index="activeIndex"
            :item="item"
            :content="statuOptions[item.index]"
            @changeOpened="onChangeOpened"
            ref="duck"
          />
          <!-- 秋天乐园 -->
          <autumn-paradise
            v-show="item.index === 2"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 私房钱 -->
          <private-money
            v-show="item.index === 3"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 小金矿 -->
          <gold-coin
            v-show="item.index === 4"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 大师兄 -->
          <brother
            v-show="item.index === 6"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 聚人气 -->
          <gather-popularity
            v-show="item.index === 7"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 小牛班 -->
          <mavericks
            v-show="item.index === 9"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 有单网 -->
          <single-network
            v-show="item.index === 10"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 宅仔 -->
          <zhai-zai
            v-show="item.index === 11"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 征服者 -->
          <conqueror
            v-show="item.index === 12"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 鸿昌科技 -->
          <hongchang
            v-show="item.index === 13"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 天玺 (差接单)-->
          <seal
            v-show="item.index === 14"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 云美贝 -->
          <yunmeibei
            v-show="item.index === 16"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 小猴子 -->
          <monkey
            v-show="item.index === 18"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 闹闹派单-->
          <noisy
            v-show="item.index === 19"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 淘助跑-->
          <run-up
            v-show="item.index === 20"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 月光宝盒-->
          <moon
            v-show="item.index === 21"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 有单做 -->
          <single
            v-show="item.index === 23"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 致承-->
          <zhi-cheng
            v-show="item.index === 27"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- D66-->
          <d66
            v-show="item.index === 28"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 美丽日记-->
          <beauty-journal
            v-show="item.index === 29"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 小黑猪 -->
          <black-pig
            v-show="item.index === 30"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 淘宝圈 -->
          <creator
            v-show="item.index === 31"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 麦家乐 -->
          <maijiale
            v-show="item.index === 32"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 优麦菜 -->
          <vegetable
            v-show="item.index === 33"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 砖圈圈 -->
          <brick-circle
            v-show="item.index === 34"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 金牛座 -->
          <taurus
            v-show="item.index === 35"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 白白赚 -->
          <white
            v-show="item.index === 36"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 如意宝 -->
          <ruyi
            v-show="item.index === 37"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 隔壁王叔叔 -->
          <uncle-wang
            v-show="item.index === 38"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 小红帽 -->
          <red-hat
            v-show="item.index === 39"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 蓝樱桃 -->
          <cherry
            v-show="item.index === 40"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 赚星星 -->
          <stars
            v-show="item.index === 41"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 飞鱼购 -->
          <!-- <flying-fish
            v-show="item.index === 42"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />-->
          <!-- 米来宝 -->
          <milaboo
            v-show="item.index === 43"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 掌萌人 -->
          <zhang-meng
            v-show="item.index === 44"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 聚峰园 -->
          <honeybee
            v-show="item.index === 45"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 冒险岛 -->
          <adventure
            v-show="item.index === 46"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 胖果果 -->
          <fruit
            v-show="item.index === 47"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
          <!-- 红树林 -->
          <mangrove
            v-show="item.index === 48"
            :index="activeIndex"
            :item="item"
            @changeOpened="onChangeOpened"
          />
        </div>
      </div>
    </van-popup>

    <!-- 验证码 -->
    <van-dialog
      v-model="isCode"
      title="验证码"
      show-cancel-button
      confirmButtonText="确认登录"
      confirmButtonColor="#000"
      @confirm="onConfirm"
      @cancel="onCancel"
    >
      <van-field v-model="code" clearable autofocus placeholder="请输入">
        <template #right-icon>
          <van-image width="100px" height="44px" fit="contain" :src="imageSrc" />
        </template>
      </van-field>
    </van-dialog>
  </div>
</template>

<script>
import { deepCopy } from "@/utils/index";
import * as api from "@/api/index";
import JingleCat from "@/components/jingle-cat";
import Duck from "@/components/duck";
import AutumnParadise from "@/components/autumn-paradise";
import PrivateMoney from "@/components/private-money";
import GoldCoin from "@/components/gold-coin";
import Brother from "@/components/brother";
import Conqueror from "@/components/conqueror";
import SingleNetwork from "@/components/single-network";
import ZhaiZai from "@/components/zhai-zai";
import Yunmeibei from "@/components/yunmeibei";
import Monkey from "@/components/monkey";
import Mavericks from "@/components/mavericks";
import Hongchang from "@/components/hongchang";
import Seal from "@/components/seal";
import RunUp from "@/components/run-up";
import Moon from "@/components/moon";
import GatherPopularity from "@/components/gather-popularity";
import Single from "@/components/single";
import ZhiCheng from "@/components/zhi-cheng";
import D66 from "@/components/D66";
import BeautyJournal from "@/components/beauty-journal";
import BlackPig from "@/components/black-pig";
import Creator from "@/components/creator";
import Noisy from "@/components/noisy";
import Maijiale from "@/components/maijiale";
import Vegetable from "@/components/vegetable";
import BrickCircle from "@/components/brick-circle";
import Taurus from "@/components/taurus";
import White from "@/components/white";
import Ruyi from "@/components/ruyi";
import UncleWang from "@/components/uncle-wang";
import RedHat from "@/components/red-hat";
import Cherry from "@/components/cherry";
import Stars from "@/components/stars";
// import FlyingFish from "@/components/flying-fish";
import Milaboo from "@/components/milaboo";
import ZhangMeng from "@/components/zhang-meng";
import Honeybee from "@/components/honeybee";
import Adventure from "@/components/adventure";
import Fruit from "@/components/fruit";
import Mangrove from "@/components/mangrove";
export default {
  name: "HomeTask",
  props: {
    active: {
      type: Number,
      default: 0
    }
  },
  components: {
    JingleCat,
    Duck,
    AutumnParadise,
    PrivateMoney,
    GoldCoin,
    Brother,
    Conqueror,
    SingleNetwork,
    ZhaiZai,
    Yunmeibei,
    Monkey,
    Mavericks,
    Hongchang,
    Seal,
    GatherPopularity,
    Single,
    RunUp,
    Moon,
    ZhiCheng,
    D66,
    BeautyJournal,
    BlackPig,
    Creator,
    Noisy,
    Maijiale,
    Vegetable,
    BrickCircle,
    Taurus,
    White,
    Ruyi,
    UncleWang,
    RedHat,
    Cherry,
    Stars,
    // FlyingFish,
    Milaboo,
    ZhangMeng,
    Honeybee,
    Adventure,
    Fruit,
    Mangrove
  },
  data() {
    return {
      iconItems: [],
      defaultArray: [],
      show: false,
      toggleAll: false,
      result: [],
      isShow: false,
      item: "",
      activeIndex: "",
      isPercentage: false,
      isCode: false,
      imageSrc: "",
      captchaKey: "",
      code: "",
      percentage: 1,
      timer: [],
      statuOptions: [],
      currentItem: "",
      currentItemIndex: "",
      currentIndex: "",
      statusHeight: ""
    };
  },
  watch: {
    // 监听复选框
    result() {
      this.toggleAll = this.result.length !== 0;
    },
    active() {
      if (this.active === 1) {
        this.iconItems =
          this.$store.getters.iconItems.length !== 0
            ? this.$store.getters.iconItems
            : this.$storage.has("iconItems")
            ? this.$storage.get("iconItems")
            : [];
      }
    },
    isShow() {
      if (this.isShow) {
        setTimeout(() => {
          this.$refs.wrapper.$el.style.paddingTop = this.statusHeight + "px";
        }, 20);
      }
    },
    show() {
      if (this.show) {
        setTimeout(() => {
          this.$refs.wrapper.$el.style.paddingTop = this.statusHeight + "px";
        }, 20);
      }
    }
  },
  created() {
    this.iconItems =
      this.$store.getters.iconItems.length !== 0
        ? this.$store.getters.iconItems
        : this.$storage.has("iconItems")
        ? this.$storage.get("iconItems")
        : [];
    this.defaultArray = deepCopy(this.iconItems);
    for (let i = 0; i < 46; i++) {
      this.statuOptions[i] = [];
    }
  },
  mounted() {
    const _this = this;
    this.$nextTick(() => {
      var statusBar = window.api.require("statusBar");
      //异步返回结果：
      statusBar.getStatusBarHeight(function(ret) {
        _this.statusHeight = ret.statusHeight;
        _this.$refs.header.$el.style.height = ret.statusHeight + 44 + "px";
        _this.$refs.header.$el.style.paddingTop = ret.statusHeight + "px";
        _this.$refs.header.$el.getElementsByClassName(
          "van-nav-bar__left"
        )[0].style.top = ret.statusHeight + "px";
        _this.$refs.header.$el.getElementsByClassName(
          "van-nav-bar__right"
        )[0].style.top = ret.statusHeight + "px";
      });
    });
  },
  methods: {
    // 一键关闭
    onClickLeft() {
      if (this.iconItems.length === 0) {
        this.$toast("请前往大厅添加平台");
      } else {
        this.$dialog
          .confirm({
            title: "提示",
            message: "请确认是否关闭所有平台",
            confirmButtonColor: "#e4393c",
            beforeClose: (action, done) => {
              done();
              if (action === "confirm") {
                // 关闭所有平台操作
              }
            }
          })
          .catch(() => {
            // on cancel
          });
      }
    },
    // 一键启动
    onClickRight() {
      if (this.iconItems.length === 0) {
        this.$toast("请前往大厅添加平台");
      } else {
        this.show = !this.show;
      }
    },
    // 全选 / 反选
    onToggleAll() {
      this.$refs.checkboxGroup.toggleAll();
    },
    // 复选
    onToggle(index) {
      this.$refs.checkboxes[index].toggle();
    },
    // 一键启动
    onSure() {
      if (this.result.length === 0) {
        this.$toast("请选择需要启动的平台");
      } else {
        this.percentage = 1;
        this.show = !this.show;
        this.isPercentage = true;
        let timer = setInterval(() => {
          this.percentage += 1;
          if ((this.percentage = this.result.length)) {
            clearInterval(timer);
            setTimeout(() => {
              this.isPercentage = !this.isPercentage;
            }, 2000);
          }
        }, 2000);
        this.onOPenFrame();
      }
    },
    // 启动平台
    onOpenPlatform(item, index) {
      if (!this.$storage.get('activationCode')) {
        window.api.openWin({
          name: "card",
          url: `./card.html`,
          bgColor: "#fff",
          pageParam: {
            active: this.active
          }
        });
      } else {
        this.item = item;
        this.activeIndex = index.toString();
        this.isShow = true;
      }
    },
    // 返回
    onBack() {
      this.activeIndex = "";
      // this.iconItems =
      //   this.$store.getters.iconItems.length !== 0
      //     ? this.$store.getters.iconItems
      //     : this.$storage.get("iconItems");
      this.isShow = !this.isShow;
    },
    // 删除
    onDelete() {
      this.$dialog
        .confirm({
          title: this.item.label,
          message: "请确认是否从任务中删除",
          confirmButtonColor: "#e4393c",
          beforeClose: (action, done) => {
            done();
            if (action === "confirm") {
              // 删除平台
              let index = this.iconItems.findIndex(
                items => items.index === this.item.index
              );
              this.iconItems.splice(index, 1);
              this.$toast("删除成功");
              this.$store.commit("SET_ICONITEMS", this.iconItems);
              this.$storage.set("iconItems", this.iconItems);
              this.isShow = !this.isShow;
              this.activeIndex = "";
            }
          }
        })
        .catch(() => {
          // on cancel
        });
    },
    // 分身
    onAdd() {
      let index = 1;
      let label = this.item.label.replace(/\d/g, "");
      this.iconItems.forEach(item => {
        if (item.label.indexOf(label) !== -1) {
          ++index;
        }
      });
      this.iconItems.push({
        label: label + index,
        hidden: false,
        opened: "待启动",
        icon: this.item.icon,
        index: this.item.index,
        user: "",
        pass: "",
        type: "",
        content: [],
        startFlag: false
      });
      this.$toast("添加成功");
      this.$store.commit("SET_ICONITEMS", this.iconItems);
      this.$storage.set("iconItems", this.iconItems);
    },
    openWin() {
      window.api.openWin({
        name: "platform",
        url: `./platform.html`,
        bgColor: "#fff",
        pageParam: {
          active: this.active
        }
      });
    },
    // 切换opened
    onChangeOpened(data) {
      this.iconItems[data.index].opened = data.status;
      this.iconItems[data.index].startFlag = data.startFlag;
      this.iconItems[data.index].content = data.content;
      this.$store.commit("SET_ICONITEMS", this.iconItems);
      this.$storage.set("iconItems", this.iconItems);
    },
    // 获取验证码
    onGetCaptcha(url) {
      this.imageSrc = "";
      this.captchaKey = api.getString32();
      this.$axios.get(url + this.captchaKey).then(() => {
        this.imageSrc = url + this.captchaKey;
      });
    },
    // 一键启动 ===>  平台
    onOPenFrame() {
      this.result.forEach((item, i) => {
        this.currentItem = item;
        this.currentItemIndex = item.index;
        this.currentIndex = i;
        if (item.index === 1) {
          // 丑小鸭
          if (item.user && item.pass) {
            item.opened = "已启动";
            this.isCode = !this.isCode;
            this.onGetCaptcha(
              "https://api.iqryznl.cn:6448/captcha/gen_img?key="
            );
          }
        }
      });
    },
    // 验证码弹窗确认
    onConfirm() {
      if (this.currentItemIndex === 1) {
        // 丑小鸭
        setTimeout(() => {
          this.statuOptions[this.currentItemIndex].push("正在登录");
        }, 3000);
      }
    },
    onCancel() {
      if (this.result.length - 1 === this.currentIndex) {
        this.isPercentage = !this.isPercentage;
      } else {
        this.percentage++;
      }
    },
    // 丑小鸭
    onStartDuck() {}
  }
};
</script>

<style lang="scss" scoped>
.home-task {
  width: 100%;
  height: calc(100vh - 50px);
  @include flex($direction: column, $flexWrap: nowrap);
  .popup-modal {
    width: 100%;
    height: 100%;
    overflow: hidden;
    @include flex(
      $direction: column,
      $flexWrap: nowrap,
      $justifyContent: flex-start
    );
  }
}
</style>

<style lang="scss">
.home-task {
  .van-nav-bar__right {
    .van-icon {
      color: #fff;
      margin-right: 10px;
      &:last-child {
        margin-right: 0;
      }
    }
  }
  .home-task__wrapper {
    width: 100%;
    flex: 1;
    overflow: hidden;
    .home-task__grid {
      .van-grid-item {
        .van-image__img {
          width: 32px;
          height: 32px;
          border-radius: 50%;
        }

        span {
          font-size: 12px;
          margin-top: 6px;
          &.home-task__grid-type {
            width: 80%;
            line-height: 20px;
            text-align: center;
            background: #ddd;
            color: #fff;
            border-radius: 22px;
            margin-bottom: 6px;
            &.active {
              background: #28d58d;
            }
            &.over {
              background: #e4393c;
            }
          }
        }
      }
    }
  }
  .van-checkbox-group {
    width: 100%;
    flex: 1;
    overflow: auto;
  }
  .popup-modal__btn {
    width: 100%;
    @include flex($flexWrap: nowrap);
    .van-button {
      flex: 1;
    }
  }
  .popup-open {
    width: 100%;
    height: 100%;
    overflow: hidden;
    @include flex(
      $direction: column,
      $flexWrap: nowrap,
      $justifyContent: flex-start
    );
    .popup-open__form {
      width: 100%;
      flex: 1;
      overflow: hidden;
      @include flex(
        $direction: column,
        $flexWrap: nowrap,
        $justifyContent: flex-start
      );
      & > div {
        width: 100%;
        flex: 1;
      }
      .van-form {
        width: 100%;
        height: calc(100% - 44px);
        overflow: auto;
      }
      .popup-open__btn {
        width: 100%;
        @include flex($flexWrap: nowrap);
        .van-button {
          flex: 1;
          &:first-child {
            flex: 0 0 120px;
          }
        }
      }
    }
  }
  .van-overlay {
    z-index: 2;
    @include flex($justifyContent: center);
    div {
      color: #fff;
      font-size: 12px;
    }
  }
  .van-popup {
    background: #e4393c;
    .popup-modal,
    .popup-open__form {
      background: #fff;
    }
  }
}
</style>